package com.ygswglxt.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ygswglxt.auth.entity.User;
import com.ygswglxt.auth.mapper.UserMapper;
import com.ygswglxt.common.JwtUtil;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {
    
    @Autowired
    private UserMapper userMapper;
    
    public Result<Map<String, Object>> login(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        
        if (user == null || !password.equals(user.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        
        if (!"ACTIVE".equals(user.getStatus())) {
            return Result.error("账号已被禁用");
        }
        
        // 禁止OTHER角色登录
        if ("OTHER".equals(user.getRole())) {
            return Result.error("该账号类型暂不支持登录");
        }
        
        String token = JwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole());
        
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userId", user.getId());
        data.put("username", user.getUsername());
        data.put("name", user.getName());
        data.put("role", user.getRole());
        
        return Result.success(data);
    }
    
    public Result<String> register(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User existUser = userMapper.selectOne(wrapper);
        if (existUser != null) {
            return Result.error("用户名已存在");
        }
        
        user.setStatus("ACTIVE");
        user.setRole("EMPLOYEE"); // 默认角色为员工
        userMapper.insert(user);
        return Result.success("注册成功");
    }
}

